class ArticlesController < ApplicationController
   before_action :authenticate?
   before_action only: [:edit, :update, :show] do
     @article = Article.find_by(params[:id])
     render 'index' unless @article
   end

   def index
     @articles = current_user.articles
   end

   def new
     @article = Article.new
   end

   def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to articles_url
    else
      render 'new'
    end
   end

   def update
     return render 'edit' unless @article
     article_snapshot = @article.article_snapshots.new(content: @article.content, version: SecureRandom.hex(10))
     if @article.update_attributes article_params
       article_snapshot.save
       @article_snapshots = @article.article_snapshots
       render 'show'
     end
   end

   def edit
   end

   def show
     @article_snapshots = @article.article_snapshots
   end

   private

   def article_params
     params.require(:article).permit(:title, :content, :image, :user_id, images_attributes: [:image])
   end
end
